<template>
  <div>
    <el-dialog :visible.sync="dialog.setting" :title="title" width="80%" append-to-body>
      <div v-for="(expressItem, index) in expressJson" :key="index">
        <div style="margin-bottom: 10px;">
          <el-tag color="error">{{expressItem.expressCompany}}</el-tag>
        </div>
        <div
          style="margin-bottom: 20px;"
          v-for="(expressData, dataIdx) in expressItem.expressData"
          :key="dataIdx"
        >
          <div v-if="!onlyView">
            <el-tag
              v-for="(expressArea, areaIdx)  in expressData.area"
              :key="areaIdx"
              color="primary"
              closable
              @close="removeProvince(expressArea.id)"
              style="margin-right: 10px;"
            >{{expressArea.province}}</el-tag>
            <el-button
              icon="el-icon-plus"
              type="warning"
              size="mini"
              @click="showAddProvince(expressItem, expressData.data)"
            >添加省</el-button>
            <el-button
              icon="el-icon-minus"
              type="danger"
              size="mini"
              @click="removeAllProvince(expressData.area)"
            >删除所有省</el-button>
          </div>
          <div v-else>
            <el-tag
              v-for="(expressArea, areaIdx)  in expressData.area"
              :key="areaIdx"
              color="primary"
              style="margin-right: 10px;"
            >{{expressArea.province}}</el-tag>
          </div>
          <div style="margin-top: 10px;">
            <el-tag type="info">是否包邮：{{expressData.data.expressFreeVal}}</el-tag>
            <el-tag type="info">规格：{{expressData.data.expressSpec}}</el-tag>
            <el-tag type="info">运费：{{expressData.data.expressFee}}</el-tag>
            <el-tag type="info">递增：{{expressData.data.incrementSpec}}</el-tag>
            <el-tag type="info">递增费用：{{expressData.data.incrementFee}}</el-tag>
            <el-tag type="info">达此金额包邮：{{expressData.data.freeMaxPayment}}</el-tag>
            <el-tag type="info">达此数量包邮：{{expressData.data.freeCondition}}</el-tag>
            <el-button
              v-if="!onlyView"
              icon="el-icon-edit"
              type="warning"
              size="mini"
              style="margin-left: 10px;"
              @click="showEdit(expressItem.expressCompany, expressData)"
            >修改</el-button>
          </div>
        </div>
      </div>
      <el-button
        v-if="!onlyView"
        icon="el-icon-plus"
        type="success"
        size="small"
        @click="showAddExpressItem"
      >新建模板项</el-button>
      <div slot="footer">
        <el-button @click="closeSetting">关闭</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialog.edit" title="修改模板数据" width="80%" append-to-body>
      <el-form ref="editForm" :model="form" label-width="120px" :rules="validateRules">
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="是否包邮" prop="expressFree">
              <el-select
                v-model="form.expressFree"
                placeholder="是否包邮"
                filterable
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="item in selects.expressFreeSelect"
                  :value="item.value"
                  :key="item.value"
                  :label="item.displayValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="快递费" prop="expressFee">
              <el-input-number v-model="form.expressFee" placeholder="请输入快递费" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="规格" prop="expressSpec">
              <el-input-number v-model="form.expressSpec" placeholder="请输入规格" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="递增规格" prop="incrementSpec">
              <el-input-number
                v-model="form.incrementSpec"
                placeholder="请输入递增规格"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="递增快递费" prop="incrementFee">
              <el-input-number
                v-model="form.incrementFee"
                placeholder="请输入递增快递费"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="包邮条件" prop="freeCondition">
              <el-input-number
                v-model="form.freeCondition"
                placeholder="请输入包邮条件"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="包邮金额" prop="freeMaxPayment">
              <el-input-number
                v-model="form.freeMaxPayment"
                placeholder="请输入包邮金额"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="closeExpress">取消</el-button>
        <el-button
          type="primary"
          @click="editExpress"
          :loading="loading.editExpress"
        >修改</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialog.province" title="添加省" width="80%" append-to-body>
      <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
        <el-checkbox
          :indeterminate="indeterminate"
          :value="checkAll"
          @click.prevent.native="checkAllProvince"
        >全选</el-checkbox>
      </div>
      <el-row :gutter="24">
        <el-checkbox-group v-model="checkedProvince" @change="checkChange">
          <el-col
            style="margin-bottom: 10px;"
            :xs="12"
            :md="6"
            :lg="4"
            v-for="(province, index) in provinceData"
            :key="index"
          >
            <el-checkbox :label="province.label"></el-checkbox>
          </el-col>
        </el-checkbox-group>
      </el-row>
      <div slot="footer">
        <el-button @click="closeProvince">取消</el-button>
        <el-button
          type="primary"
          @click="saveProvinceExpress"
          :loading="loading.saveProvinceExpress"
        >添加</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialog.add" title="新建模板" width="80%" append-to-body>
      <el-form ref="addForm" :model="form" label-width="120px" :rules="validateRules">
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="物流公司" prop="expressCompany">
              <el-select
                v-model="form.expressCompany"
                placeholder="请选择物流公司"
                filterable
                @change="selectCompany"
                style="width: 100%;"
              >
                <el-option value="普通快递">普通快递</el-option>
                <el-option value="骑手配送">骑手配送</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="是否包邮" prop="expressFree">
              <el-select
                v-model="form.expressFree"
                placeholder="是否包邮"
                filterable
                clearable
                style="width: 100%;"
              >
                <el-option
                  v-for="item in selects.expressFreeSelect"
                  :value="item.value"
                  :key="item.value"
                  :label="item.displayValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="快递费" prop="expressFee">
              <el-input-number v-model="form.expressFee" placeholder="请输入快递费" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="规格" prop="expressSpec">
              <el-input-number v-model="form.expressSpec" placeholder="请输入规格" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="递增规格" prop="incrementSpec">
              <el-input-number
                v-model="form.incrementSpec"
                placeholder="请输入递增规格"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="递增快递费" prop="incrementFee">
              <el-input-number
                v-model="form.incrementFee"
                placeholder="请输入递增快递费"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="包邮条件" prop="freeCondition">
              <el-input-number
                v-model="form.freeCondition"
                placeholder="请输入包邮条件"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="8">
            <el-form-item label="包邮金额" prop="freeMaxPayment">
              <el-input-number
                v-model="form.freeMaxPayment"
                placeholder="请输入包邮金额"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
        <span style="margin-right: 20px;">选择目的地</span>
        <el-checkbox
          :indeterminate="indeterminate"
          :value="checkAll"
          @click.prevent.native="checkAllProvince"
        >全选</el-checkbox>
      </div>
      <el-row :gutter="24">
        <el-checkbox-group v-model="checkedProvince" @change="checkChange">
          <el-col
            style="margin-bottom: 10px;"
            :xs="12"
            :md="6"
            :lg="4"
            v-for="(province, index) in provinceData"
            :key="index"
          >
            <el-checkbox :label="province.label"></el-checkbox>
          </el-col>
        </el-checkbox-group>
      </el-row>
      <div slot="footer">
        <el-button @click="closeAdd">取消</el-button>
        <el-button
          type="primary"
          @click="saveExpress"
          :loading="loading.saveExpress"
        >添加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as utils from '@/utils/utils'
import * as ResponseStatus from '@/utils/response-status'
import { convertJson } from '@/api/express'
import { provinceData } from '@/api/province'
export default {
  name: 'ExpressTemplateSettingDialog',
  props: {
    title: {
      type: String,
      defalut: '设置运费模板项'
    },
    onlyView: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialog: {
        setting: false,
        add: false,
        edit: false,
        province: false
      },
      loading: {
        saveExpress: false,
        editExpress: false,
        saveProvinceExpress: false
      },
      form: {
        templateId: undefined,
        templateTitle: undefined,
        templateIsActive: undefined,
        expressCompany: '普通快递',
        province: undefined,
        city: undefined,
        district: undefined,
        expressFree: undefined,
        expressFee: undefined,
        expressSpec: undefined,
        incrementSpec: undefined,
        incrementFee: undefined,
        freeCondition: undefined,
        freeMaxPayment: undefined
      },
      validateRules: {
        templateId: [
          {
            type: 'integer',
            required: true,
            message: '此项为必须项',
            trigger: 'blur, change'
          }
        ],
        expressCompany: [
          {
            type: 'string',
            required: true,
            message: '此项为必须项',
            trigger: 'blur'
          },
          {
            type: 'string',
            min: 1,
            max: 255,
            message: '必须1-255个字符',
            trigger: 'blur'
          }
        ],
        province: [
          {
            type: 'string',
            required: true,
            message: '此项为必须项',
            trigger: 'blur'
          },
          {
            type: 'string',
            min: 1,
            max: 50,
            message: '必须1-50个字符',
            trigger: 'blur'
          }
        ],
        city: [
          {
            type: 'string',
            min: 1,
            max: 50,
            message: '必须1-50个字符',
            trigger: 'blur'
          }
        ],
        district: [
          {
            type: 'string',
            min: 1,
            max: 50,
            message: '必须1-50个字符',
            trigger: 'blur'
          }
        ],
        expressFree: [
          {
            type: 'integer',
            required: true,
            message: '此项为必须项',
            trigger: 'blur, change'
          }
        ],
        expressFee: [
          {
            type: 'number',
            required: true,
            message: '此项为必须项',
            trigger: 'blur, change'
          }
        ],
        expressSpec: [
          {
            type: 'number',
            required: true,
            message: '此项为必须项',
            trigger: 'blur, change'
          }
        ]
      },
      dataDictCodes: ['YES_NO'],
      dataDictItems: {},
      selects: {
        expressFreeSelect: [],
      },
      expressJson: {},
      provinceData: [],
      checkedProvince: [],
      checkAll: false,
      indeterminate: false,
      checkedExpressCompany: null,
      checkedExpressData: {},
      toEditExpressData: {}
    }
  },
  computed: {},
  mounted() {
    this.provinceData = provinceData
    utils
      .getDataDict(this.dataDictCodes)
      .then(response => {
        if (response) {
          this.dataDictItems = response
        }
      })
      .catch(error => {})
  },
  methods: {
    loadExpressTemplateItems(template) {
      this.expressJson = {}
      this.form.templateId = template.id
      this.form.templateTitle = template.title
      utils
        .doPostJson(
          '/express-template-item/admin/all-cond',
          {
            templateId: template.id,
            sortColumn: 'createTime',
            sortOrder: 'asc'
          },
          {}
        )
        .then(response => {
          if (response.data.rows.length > 0) {
            this.expressJson = convertJson(response.data.rows)
            for (
              let i = 0, len = this.expressJson[0].expressData.length;
              i < len;
              i++
            ) {
              let data = this.expressJson[0].expressData[i]
              this.expressJson[0].expressData[
                i
              ] = this.getDetailDictItemDisplayValue(
                data,
                'YES_NO',
                'expressFree'
              )
            }
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getDetailDictItemDisplayValue(expressData, dictCode, formProp) {
      let dictItems = this.dataDictItems[dictCode]
      if (dictItems !== undefined && dictItems.length > 0) {
        for (let i = 0, len = dictItems.length; i < len; i++) {
          if (expressData.data[formProp] === dictItems[i].value) {
            expressData.data[formProp] = expressData.data[formProp]
            expressData.data[formProp + 'Val'] = dictItems[i].displayValue
            return expressData
          }
        }
      }
    },
    removeProvince(expressItemId) {
      this.$confirm('确认删除选择的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          utils
            .doGet('/express-template-item/admin/remove/' + expressItemId, {})
            .then(response => {
              this.loadExpressTemplateItems({id: this.form.templateId, title: this.form.templateTitle})
              this.provinceData = provinceData
            })
            .catch(error => {
              console.log(error)
            })
        })
        .catch(() => {})
    },
    showAddProvince(expressItem, data) {
      this.dialog.province = true
      this.provinceData = provinceData
      let allExistProvince = []
      // 需要把同一个快递的所有已配置运费的省去除
      expressItem.expressData.forEach(item => {
        item.area.forEach(province => {
          allExistProvince.push(province)
        })
      })
      this.checkedExpressCompany = expressItem.expressCompany
      this.checkedExpressData = data
      for (let i = 0, len = allExistProvince.length; i < len; i++) {
        this.provinceData = this.provinceData.filter(item => {
          return item.label != allExistProvince[i].province
        })
      }
    },
    removeAllProvince(areas) {
      this.$confirm('确认删除选择的数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let ids = []
          areas.forEach(area => {
            ids.push(area.id)
          })
          utils
            .doPostJson('/express-template-item/admin/batch-remove', ids, {})
            .then(response => {
              this.loadExpressTemplateItems({id: this.form.templateId, title: this.form.templateTitle})
              this.provinceData = provinceData
            })
            .catch(error => {
              console.log(error)
            })
        })
        .catch(() => {})
    },
    closeSetting() {
      this.dialog.setting = false
    },
    checkAllProvince() {
      if (this.checkAll) {
        this.checkedProvince = []
      } else {
        this.provinceData.forEach(province => {
          this.checkedProvince.push(province.label)
        })
      }
      this.checkAll = !this.checkAll
      this.indeterminate = false
    },
    checkChange() {
      this.checkAll = this.checkedProvince.length === this.provinceData.length
      if (
        this.checkedProvince.length > 0 &&
        this.checkedProvince.length < this.provinceData.length
      ) {
        this.indeterminate = true
      } else {
        this.indeterminate = false
      }
    },
    showEdit(expressCompany, expressData) {
      this.dialog.edit = true
      utils.getSelectDictItems({
            mainComponent: this,
            dataDictItems: this.dataDictItems,
            dictCode: 'YES_NO',
            formProp: 'expressFree',
            dataProp: 'expressFreeSelect'
          })
      this.toEditExpressData = expressData
      this.form.expressCompany = expressCompany
      this.form.expressFree = expressData.data.expressFree
      this.form.expressFreeValue = expressData.data.expressFreeVal
      this.form.expressFee = expressData.data.expressFee
      this.form.expressSpec = expressData.data.expressSpec
      this.form.incrementSpec = expressData.data.incrementSpec
      this.form.incrementFee = expressData.data.incrementFee
      this.form.freeMaxPayment = expressData.data.freeMaxPayment
      this.form.freeCondition = expressData.data.freeCondition
    },
    showAddExpressItem() {
      this.dialog.add = true
      this.selectCompany(this.form.expressCompany)
      utils.getSelectDictItems({
            mainComponent: this,
            dataDictItems: this.dataDictItems,
            dictCode: 'YES_NO',
            formProp: 'expressFree',
            dataProp: 'expressFreeSelect'
          })
    },
    add() {
      this.$emit('add')
    },
    edit() {
      this.$emit('edit')
    },
    saveProvinceExpress() {
      if (this.checkedProvince.length === 0) {
        this.$message.warning('请先选择需要添加的省')
      }
      let data = []
      this.checkedProvince.forEach(province => {
        data.push({
          templateId: this.form.templateId,
          templateTitle: this.form.templateTitle,
          templateIsActive: 1,
          expressCompany: this.checkedExpressCompany,
          province: province,
          expressFree: this.checkedExpressData.expressFree,
          expressFee: this.checkedExpressData.expressFee,
          expressSpec: this.checkedExpressData.expressSpec,
          incrementSpec: this.checkedExpressData.incrementSpec,
          incrementFee: this.checkedExpressData.incrementFee,
          freeMaxPayment: this.checkedExpressData.freeMaxPayment,
          freeCondition: this.checkedExpressData.freeCondition
        })
      })
      utils
        .doPostJson('/express-template-item/admin/batch-save', data, {})
        .then(response => {
          this.$message.success('添加成功')
          this.dialog.province = false
          this.checkedProvince = []
          this.loadExpressTemplateItems({id: this.form.templateId, title: this.form.templateTitle})
          this.provinceData = provinceData
        })
        .catch(error => {
          console.log(error)
        })
    },
    selectCompany(expressCompany) {
      if (expressCompany) {
        this.provinceData = provinceData
        let allExistProvince = []
        // 需要把同一个快递的所有已配置运费的省去除
        for (let i = 0, len = this.expressJson.length; i < len; i++) {
          if (this.expressJson[i].expressCompany === expressCompany) {
            this.expressJson[i].expressData.forEach(expressData => {
              expressData.area.forEach(area => {
                allExistProvince.push(area)
              })
            })
            break
          }
        }
        for (let i = 0, len = allExistProvince.length; i < len; i++) {
          this.provinceData = this.provinceData.filter(item => {
            return item.label != allExistProvince[i].province
          })
        }
      }
      this.checkedProvince = []
      this.indeterminate = false
    },
    saveExpress() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.checkedProvince.length === 0) {
            this.$message.warning('请先选择需要添加的省')
            return
          }
          let data = []
          this.checkedProvince.forEach(province => {
            data.push({
              templateId: this.form.templateId,
              templateTitle: this.form.templateTitle,
              templateIsActive: 1,
              province: province,
              expressCompany: this.form.expressCompany,
              expressFree: this.form.expressFree,
              expressFee: this.form.expressFee,
              expressSpec: this.form.expressSpec,
              incrementSpec: this.form.incrementSpec,
              incrementFee: this.form.incrementFee,
              freeMaxPayment: this.form.freeMaxPayment,
              freeCondition: this.form.freeCondition
            })
          })
          this.loading.saveExpress = true
          utils
            .doPostJson('/express-template-item/admin/batch-save', data, {})
            .then(response => {
              this.$message.success('新建运费模板成功')
              this.dialog.add = false
              this.loadExpressTemplateItems({id: this.form.templateId, title: this.form.templateTitle})
              this.loading.saveExpress = false
              this.checkedProvince = []
              this.indeterminate = false
            })
            .catch(error => {
              this.loading.saveExpress = false
              console.log(error)
            })
        }
      })
    },
    editExpress() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          let data = []
          this.toEditExpressData.area.forEach(area => {
            data.push({
              id: area.id,
              templateId: this.form.templateId,
              templateTitle: this.form.templateTitle,
              province: area.province,
              expressCompany: this.form.expressCompany,
              expressFree: this.form.expressFree,
              expressFee: this.form.expressFee,
              expressSpec: this.form.expressSpec,
              incrementSpec: this.form.incrementSpec,
              incrementFee: this.form.incrementFee,
              freeMaxPayment: this.form.freeMaxPayment,
              freeCondition: this.form.freeCondition
            })
          })
          this.loading.editExpress = true
          utils
            .doPostJson('/express-template-item/admin/batch-update', data, {})
            .then(response => {
              this.$message.success('修改成功')
              this.dialog.edit = false
              this.checkedProvince = []
              this.loadExpressTemplateItems({id: this.form.templateId, title: this.form.templateTitle})
              this.loading.editExpress = false
            })
            .catch(error => {
              console.log(error)
              this.loading.editExpress = false
            })
        }
      })
    },
    closeProvince() {
      this.dialog.province = false
      this.checkedProvince = []
      this.indeterminate = false
      this.checkAll = false
    },
    closeAdd() {
      this.dialog.add = false
      this.checkedProvince = []
      this.indeterminate = false
      this.$refs.addForm.resetFields()
    },
    closeExpress() {
      this.dialog.edit = false
      this.$refs.editForm.resetFields()
    }
  }
}
</script>

<style>
</style>
